package org.example.demo.Demo02;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;


public class DataSource {

    public static void main(String[] args) {
        //定义MYSQL数据源对象
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        //社长数据库的连接串
        mysqlDataSource.setURL("jdbc:");
        //设置用户名
        mysqlDataSource.setUser("root");
        //设置密码
        mysqlDataSource.setPassword("123456");
        //定义JDBC的数据源对象
        MysqlDataSource dataSource = mysqlDataSource;
        //声明数据库连接对象
        Connection connection = null;
        //声明Sql语句预处理对象
        PreparedStatement statement = null;
        //声明
        ResultSet resultSet = null;

        try {
            // 1.获取数据库连接
            connection = dataSource.getConnection();
            //2.定义sql语句
            String sql = "select id,name,age from student where name=?  ";
            //String sql="select id,name,age from student where name=? and age=?  ";
            //接收用户输入的姓名
            System.out.println("请输入要查询的姓名-->");
            Scanner scanner = new Scanner(System.in);
            String inputName = scanner.next();
            //3.获取sql预处理对象
            statement = connection.prepareStatement(sql);
            //4.用真实姓名去替换占位符
            statement.setString(1, inputName);
            //5.执行sql语句
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                //每进入一次循环表示读取了一行记录
                // 获取ID列的值,根据列的数据类型调用不同的方法
                long id = resultSet.getLong("id");
                //依次获取其他列的值
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                //打印结果
                System.out.println(MessageFormat.format("学生编号={0}，姓名={1}，年龄={2}", id, name, age));


            }

        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        } finally {
            //依次释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }


            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }
}
